import {useEffect, useState} from "react";
import {connect} from "react-redux";
import {Button, Form, Input, Toast} from 'antd-mobile'
import NavbarAgain from "../components/NavbarAgain";
import action from '../store/action'
import './Login.less'
import api from "../api";
import _ from '@/assets/utils.js'

const Login = (props) => {
    console.log(props)
    const { getUserInfo , navigate , query } = props
    const [form] = Form.useForm()
    const [sedText, setSedText] = useState('发送验证码')
    const [disabled, setDisabled] = useState(false)
    // 组件销毁的时候:把没有清除的定时器干掉
    useEffect(() => {
        return () => {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        }
    }, []);
    // 自定义校验
    const validator =  {
        phone(_, value) {
            value = value ?  value.trim() : ''
            const reg = /^(?:(?:\+|00)86)?1\d{10}$/
            if(value.length === 0) return Promise.reject(new Error('手机号不能为空'))
            if(!reg.test(value)) return Promise.reject(new Error('手机号格式不正确'))
            return Promise.resolve()
        },
        code(_, value) {
            value = value ?  value.trim() : ''
            const reg = /^\d{6}$/
            if(value.length === 0) return Promise.reject(new Error('验证码不能为空'))
            if(!reg.test(value)) return Promise.reject(new Error('验证码格式不正确'))
            return Promise.resolve()
        }
    }

    let num = 5
    let timer = null

    // 发送验证码
    const sending = async() => {

        try {
            await form.validateFields(['phone'])
            let { phone } = form.getFieldValue(),
                data = await api.sendPhoneCode(phone)
            console.log(data)
            if(data.codeText === "OK"){
                setDisabled(true)
                if(!timer){
                   timer = setInterval(()=>{
                        countdown()
                    },1000)
                }


            }
        }catch (_){
            console.log(_)
        }

    }
    // 倒计时
    const countdown = () => {
        num--
        if(num === 0){
            setSedText('发送验证码')
            clearInterval(timer)
            timer = null
            setDisabled(false)
        }else{
            setSedText(`${num} s后重发`)
        }
    }
    // 提交
    const onSubmit = async () => {
        try{
            await form.validateFields()
            let { phone , code} = form.getFieldValue()

            // const {code: codeHttp , token} = await api.login({phone,code})
            // if(+codeHttp !== 0){
            //    return Toast.show({
            //         icon:'fail',
            //         content:'登录失败'
            //     })
            // }
            // 登录成功，存储token
            // _.storage.set('tk',token)

            _.storage.set('tk','token')
            // 获取用户信息
            await getUserInfo()
            Toast.show({
                icon:'success',
                content:'登录成功'
            })

            // 获取路径参数
            // 如果有跳转目标（没token才来登录）就去之前目标
            let to = query.get('to')
            to ? navigate(to, {replace:true}) : navigate(-1)

        }catch (_){}

    }


    return <div className='login-box'>
        <NavbarAgain title={'登录/注册'}/>
        <Form layout='horizontal' mode='card' form={form}
              style={{ '--border-top': 'none' }}
              requiredMarkStyle= 'none'
              footer={
                  <Button block color='primary' type={'submit'} onClick={onSubmit}>
                      提交
                  </Button>
              }

              initialValues={{
                  photo:'',code:''
              }}
        >
            <Form.Item name='phone' label='手机号' rules={[{ validator : validator.phone}]}>
                <Input placeholder='请输入手机号' />
            </Form.Item>
            <Form.Item name='code' label='验证码'
                       rules={[{ validator : validator.code}]}
                       extra={
                            <Button color='primary' size='small' disabled={disabled} onClick={sending}>{sedText}</Button>
            }>
                <Input placeholder='请输入' />
            </Form.Item>
        </Form>
    </div>
}

export default connect(
    null,
    action.user
)(Login)
